package com.sto.stoapp.activity.administrator.system;

import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHomeActivity;

public class SystemAutoCloseScreenTimeActivity extends StoHomeActivity {

	private Button saveBtn;

	private EditText timeEdit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.admin_close_screen_time);
		String broadType = getIntent().getStringExtra(
				HomeBroadAction.BROAD_TYPE);
		this.setTitleBottom(R.string.system_auto_close_screen, broadType);
		initWidget();
		initListener();
	}


	private void initListener() {
		saveBtn.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View view) {
				saveSet();
			}
		});
		timeEdit.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View view) {

				// saveSet();
			}
		});
	}

	private void saveSet() {
		String time = timeEdit.getText().toString();
		if (time.equals("") || !Helper.isNumeric(time)) {
			Helper.showToast(SystemAutoCloseScreenTimeActivity.this,
					getText(R.string.edit_invalid_digit).toString());
		} else {

			setTimeoutLocked();
		}
	}

	private void initWidget() {
		saveBtn = (Button) findViewById(R.id.save);
		timeEdit = (EditText) findViewById(R.id.time_edit);
		timeEdit.setText(StoFilePreference.getInstance(this)
				.getSystemCloseScreenTime() + "");
		Helper.setCursorEnd(timeEdit);
	}

	/**
	 * 设置超时时间
	 */
	private void setTimeoutLocked() {
		try {
			int time = Integer.parseInt(timeEdit.getText().toString());
			if (time == 0) {
				Settings.System.putInt(this.getContentResolver(),
						Settings.System.SCREEN_OFF_TIMEOUT, -1);
				finish();
			}
			if (time > 1200 || time < 180) {
				Helper.showSoundToast(
						SystemAutoCloseScreenTimeActivity.this,
						this.getString(R.string.set_time_out_second).toString(),
						false);
			} else {
				StoFilePreference.getInstance(
						SystemAutoCloseScreenTimeActivity.this)
						.setSystemCloseScreenTime(time);
				Settings.System.putInt(this.getContentResolver(),
						Settings.System.SCREEN_OFF_TIMEOUT, time * 1000);
				Helper.showToast(SystemAutoCloseScreenTimeActivity.this,
						getText(R.string.save_success).toString());
				finish();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
